import {
  ToolUsage,
  ToolAnalysisConfig,
  PromptBuildContext
} from './types';

/**
 * 工具使用模式
 */
export interface ToolUsagePattern {
  toolName: string;
  frequency: number;
  successRate: number;
  averageDuration: number;
  commonInputs: any[];
  commonOutputs: any[];
  contextPatterns: string[];
}

/**
 * 工具分析结果
 */
export interface ToolAnalysisResult {
  patterns: ToolUsagePattern[];
  recommendations: string[];
  relevantHistory: ToolUsage[];
  summary: string;
}

/**
 * 工具历史分析器
 * 负责分析工具使用历史并提取有用的模式和建议
 */
export class ToolHistoryAnalyzer {
  private config: ToolAnalysisConfig;
  private toolHistory: ToolUsage[] = [];

  constructor(config?: ToolAnalysisConfig) {
    this.config = config || this.getDefaultConfig();
  }

  /**
   * 添加工具使用记录
   */
  addToolUsage(usage: ToolUsage): void {
    this.toolHistory.push(usage);
    
    // 保持历史记录在配置的最大数量内
    if (this.toolHistory.length > this.config.maxToolHistory) {
      this.toolHistory = this.toolHistory.slice(-this.config.maxToolHistory);
    }
  }

  /**
   * 批量添加工具使用记录
   */
  addToolUsages(usages: ToolUsage[]): void {
    for (const usage of usages) {
      this.addToolUsage(usage);
    }
  }

  /**
   * 分析工具使用历史
   */
  analyzeToolHistory(context: PromptBuildContext): ToolAnalysisResult {
    const relevantHistory = this.getRelevantHistory(context);
    const patterns = this.config.patternAnalysis 
      ? this.extractUsagePatterns(relevantHistory)
      : [];
    
    const recommendations = this.generateRecommendations(patterns, context);
    const summary = this.generateSummary(patterns, relevantHistory);

    return {
      patterns,
      recommendations,
      relevantHistory,
      summary
    };
  }

  /**
   * 获取相关的工具历史
   */
  private getRelevantHistory(context: PromptBuildContext): ToolUsage[] {
    let relevantHistory = [...this.toolHistory];

    // 按时间排序（最新的在前）
    relevantHistory.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());

    // 如果启用了成功率加权，优先选择成功的工具使用
    if (this.config.successRateWeighting) {
      const successful = relevantHistory.filter(usage => usage.success);
      const failed = relevantHistory.filter(usage => !usage.success);
      
      // 成功的记录占70%，失败的记录占30%
      const successfulCount = Math.floor(this.config.maxToolHistory * 0.7);
      const failedCount = this.config.maxToolHistory - successfulCount;
      
      relevantHistory = [
        ...successful.slice(0, successfulCount),
        ...failed.slice(0, failedCount)
      ];
    }

    // 如果启用了上下文分组，按相似上下文分组
    if (this.config.contextualGrouping) {
      relevantHistory = this.groupByContext(relevantHistory, context);
    }

    return relevantHistory.slice(0, this.config.maxToolHistory);
  }

  /**
   * 提取使用模式
   */
  private extractUsagePatterns(history: ToolUsage[]): ToolUsagePattern[] {
    const toolGroups = this.groupByTool(history);
    const patterns: ToolUsagePattern[] = [];

    for (const [toolName, usages] of toolGroups.entries()) {
      if (usages.length < 2) continue; // 至少需要2次使用才能形成模式

      const pattern = this.analyzeToolPattern(toolName, usages);
      patterns.push(pattern);
    }

    // 按频率排序
    return patterns.sort((a, b) => b.frequency - a.frequency);
  }

  /**
   * 按工具名称分组
   */
  private groupByTool(history: ToolUsage[]): Map<string, ToolUsage[]> {
    const groups = new Map<string, ToolUsage[]>();
    
    for (const usage of history) {
      const existing = groups.get(usage.toolName) || [];
      existing.push(usage);
      groups.set(usage.toolName, existing);
    }
    
    return groups;
  }

  /**
   * 分析单个工具的使用模式
   */
  private analyzeToolPattern(toolName: string, usages: ToolUsage[]): ToolUsagePattern {
    const successfulUsages = usages.filter(u => u.success);
    const successRate = successfulUsages.length / usages.length;
    
    const durations = usages
      .filter(u => u.duration !== undefined)
      .map(u => u.duration!);
    const averageDuration = durations.length > 0 
      ? durations.reduce((sum, d) => sum + d, 0) / durations.length
      : 0;

    const commonInputs = this.extractCommonInputs(usages);
    const commonOutputs = this.extractCommonOutputs(successfulUsages);
    const contextPatterns = this.extractContextPatterns(usages);

    return {
      toolName,
      frequency: usages.length,
      successRate,
      averageDuration,
      commonInputs,
      commonOutputs,
      contextPatterns
    };
  }

  /**
   * 提取常见输入
   */
  private extractCommonInputs(usages: ToolUsage[]): any[] {
    const inputCounts = new Map<string, number>();
    
    for (const usage of usages) {
      const inputStr = JSON.stringify(usage.input);
      inputCounts.set(inputStr, (inputCounts.get(inputStr) || 0) + 1);
    }

    // 返回出现频率最高的前5个输入
    return Array.from(inputCounts.entries())
      .sort((a, b) => b[1] - a[1])
      .slice(0, 5)
      .map(([inputStr]) => JSON.parse(inputStr));
  }

  /**
   * 提取常见输出
   */
  private extractCommonOutputs(usages: ToolUsage[]): any[] {
    const outputCounts = new Map<string, number>();
    
    for (const usage of usages) {
      if (usage.output) {
        const outputStr = JSON.stringify(usage.output);
        outputCounts.set(outputStr, (outputCounts.get(outputStr) || 0) + 1);
      }
    }

    // 返回出现频率最高的前3个输出
    return Array.from(outputCounts.entries())
      .sort((a, b) => b[1] - a[1])
      .slice(0, 3)
      .map(([outputStr]) => JSON.parse(outputStr));
  }

  /**
   * 提取上下文模式
   */
  private extractContextPatterns(usages: ToolUsage[]): string[] {
    const patterns: string[] = [];
    
    // 分析时间模式
    const hours = usages.map(u => u.timestamp.getHours());
    const hourCounts = this.countOccurrences(hours);
    const peakHour = this.getMostFrequent(hourCounts);
    if (peakHour !== null) {
      patterns.push(`Most used during hour ${peakHour}`);
    }

    // 分析序列模式
    const sequences = this.findToolSequences(usages);
    if (sequences.length > 0) {
      patterns.push(`Often used in sequence: ${sequences.join(', ')}`);
    }

    return patterns;
  }

  /**
   * 计算出现次数
   */
  private countOccurrences<T>(items: T[]): Map<T, number> {
    const counts = new Map<T, number>();
    for (const item of items) {
      counts.set(item, (counts.get(item) || 0) + 1);
    }
    return counts;
  }

  /**
   * 获取最频繁的项
   */
  private getMostFrequent<T>(counts: Map<T, number>): T | null {
    let maxCount = 0;
    let mostFrequent: T | null = null;
    
    for (const [item, count] of counts.entries()) {
      if (count > maxCount) {
        maxCount = count;
        mostFrequent = item;
      }
    }
    
    return mostFrequent;
  }

  /**
   * 查找工具序列
   */
  private findToolSequences(usages: ToolUsage[]): string[] {
    // 简化实现：查找连续使用的工具对
    const sequences: string[] = [];
    
    for (let i = 0; i < usages.length - 1; i++) {
      const current = usages[i];
      const next = usages[i + 1];
      
      // 如果两个工具使用时间间隔小于5分钟，认为是序列
      const timeDiff = next.timestamp.getTime() - current.timestamp.getTime();
      if (timeDiff < 5 * 60 * 1000) {
        const sequence = `${current.toolName} → ${next.toolName}`;
        if (!sequences.includes(sequence)) {
          sequences.push(sequence);
        }
      }
    }
    
    return sequences;
  }

  /**
   * 按上下文分组
   */
  private groupByContext(history: ToolUsage[], context: PromptBuildContext): ToolUsage[] {
    // 简化实现：优先选择与当前上下文相关的工具使用
    const contextual: ToolUsage[] = [];
    const general: ToolUsage[] = [];
    
    for (const usage of history) {
      if (this.isContextuallyRelevant(usage, context)) {
        contextual.push(usage);
      } else {
        general.push(usage);
      }
    }
    
    // 优先返回上下文相关的，然后是一般的
    return [...contextual, ...general];
  }

  /**
   * 检查工具使用是否与当前上下文相关
   */
  private isContextuallyRelevant(usage: ToolUsage, context: PromptBuildContext): boolean {
    // 检查工具元数据中的上下文信息
    if (usage.metadata?.context) {
      const usageContext = usage.metadata.context;
      
      // 检查文件路径匹配
      if (usageContext.filePath && context.codeContext?.currentFile?.path) {
        if (usageContext.filePath === context.codeContext.currentFile.path) {
          return true;
        }
      }
      
      // 检查聊天模式匹配
      if (usageContext.chatMode === context.mode) {
        return true;
      }
    }
    
    return false;
  }

  /**
   * 生成建议
   */
  private generateRecommendations(
    patterns: ToolUsagePattern[],
    context: PromptBuildContext
  ): string[] {
    const recommendations: string[] = [];
    
    for (const pattern of patterns.slice(0, 3)) { // 只考虑前3个最频繁的模式
      if (pattern.successRate < 0.5) {
        recommendations.push(
          `Consider reviewing usage of ${pattern.toolName} - low success rate (${Math.round(pattern.successRate * 100)}%)`
        );
      }
      
      if (pattern.averageDuration > 10000) { // 超过10秒
        recommendations.push(
          `${pattern.toolName} takes an average of ${Math.round(pattern.averageDuration / 1000)}s - consider optimizing inputs`
        );
      }
      
      if (pattern.commonInputs.length > 0) {
        recommendations.push(
          `${pattern.toolName} is commonly used with similar inputs - consider creating shortcuts`
        );
      }
    }
    
    return recommendations;
  }

  /**
   * 生成摘要
   */
  private generateSummary(patterns: ToolUsagePattern[], history: ToolUsage[]): string {
    if (history.length === 0) {
      return "No tool usage history available.";
    }
    
    const totalUsages = history.length;
    const successfulUsages = history.filter(u => u.success).length;
    const overallSuccessRate = successfulUsages / totalUsages;
    const uniqueTools = new Set(history.map(u => u.toolName)).size;
    
    let summary = `Used ${uniqueTools} different tools ${totalUsages} times with ${Math.round(overallSuccessRate * 100)}% success rate.`;
    
    if (patterns.length > 0) {
      const mostUsedTool = patterns[0];
      summary += ` Most frequently used: ${mostUsedTool.toolName} (${mostUsedTool.frequency} times).`;
    }
    
    return summary;
  }

  /**
   * 清空工具历史
   */
  clearHistory(): void {
    this.toolHistory = [];
  }

  /**
   * 获取工具统计
   */
  getToolStats(): {
    totalUsages: number;
    uniqueTools: number;
    overallSuccessRate: number;
    averageDuration: number;
  } {
    const totalUsages = this.toolHistory.length;
    const uniqueTools = new Set(this.toolHistory.map(u => u.toolName)).size;
    const successfulUsages = this.toolHistory.filter(u => u.success).length;
    const overallSuccessRate = totalUsages > 0 ? successfulUsages / totalUsages : 0;
    
    const durations = this.toolHistory
      .filter(u => u.duration !== undefined)
      .map(u => u.duration!);
    const averageDuration = durations.length > 0 
      ? durations.reduce((sum, d) => sum + d, 0) / durations.length
      : 0;

    return {
      totalUsages,
      uniqueTools,
      overallSuccessRate,
      averageDuration
    };
  }

  /**
   * 获取默认配置
   */
  private getDefaultConfig(): ToolAnalysisConfig {
    return {
      maxToolHistory: 50,
      patternAnalysis: true,
      successRateWeighting: true,
      contextualGrouping: true
    };
  }
}
